﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace EnglishWordsAnalyster
{
    public class WordInfo
    {
        private string meaning;

        public WordInfo(string word, string meaning)
        {
            this.Word = word;
            this.meaning = meaning;
        }
        public int ID { get; set; }

        public string Word { get; set; }

        public List<ClassInfo> Meaning { get; set; }

        public void SetMeaning(string theMeaning)
        {
            Meaning = new List<ClassInfo>();

            MatchCollection mc;

            String[] results = new String[20];

            int[] matchposition = new int[20];

            Regex r = new Regex(@"[a-z,A-Z]+\."); //定义一个Regex对象实例

            mc = r.Matches(meaning);

            int spot = 0; 
            
            for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                spot = GetEndPos(mc,i);
                ClassInfo info = new ClassInfo() {Word=this.Word,Class=GetClass(mc[i]),Definition=GetDefinition(mc[i],spot) };
                
                if (!Meaning.Any<ClassInfo>(x => x.Class == info.Class))
                {
                    Meaning.Add(info);
                }

                
            }

            
        }

        private string GetDefinition(Match match, int spot)
        {
            try
            {

                int index = match.Index + match.Value.Length;

                int length = spot - index+1;

                return meaning.Substring(index, length);
            }
            catch
            {
                return "";
            }
        }

        private int GetEndPos(MatchCollection mc, int i)
        {
            if (i+1>=mc.Count)
            {
                return meaning.Length - 1-1;
            }

            return mc[i + 1].Index-1;
        }



        private string GetClass(Match match)
        {
            try
            {
                int point = match.Value.IndexOf('.');
                return match.Value.Substring(0, point);
            }
            catch 
            {
                return "";
            }

        }



    }

    public class ClassInfo
    {
        public string Word { get; set; }

        public string Class { get; set; }

        public string Definition { get; set; }


    }

}
